# encoding=utf-8
# author:梁子龙
from rest_framework import serializers
from .models import UserModel, AddressModel


"""
1.
 user = serializers.SerializerMethodField()
  # def get_user(self, obj):
    #     return obj.user.username  # 或者返回用户对象的其他字段，如 `obj.user.username`

2.
    user = serializers.SlugRelatedField(slug_field="username", read_only=True)

3.

"""


class AddressSerializer(serializers.ModelSerializer):
    # user = serializers.SerializerMethodField()
    user = serializers.SlugRelatedField(slug_field="username", read_only=True)



    class Meta:
        model = AddressModel
        fields = '__all__'
    #
    # def get_user(self, obj):
    #     return obj.user.username  # 或者返回用户对象的其他字段，如 `obj.user.username`


class UserSerializer(serializers.ModelSerializer):
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    full_name = serializers.SerializerMethodField()
    # addresses = serializers.SlugRelatedField(slug_field="addresses.province", read_only=True)

    # addresses = AddressSerializer(many=True, read_only=True)
    # full_address = serializers.SerializerMethodField()

    # addresses = AddressSerializer(many=True, read_only=True)

    class Meta:
        model = UserModel

        # fields = ["id", "username", "phone", "email", "real_name", "date_joined", "addresses"]
        fields = ["id", "username", "phone", "email", "real_name", "date_joined", "addresses", "full_name"]
        # depth = 1

    def get_full_name(self, obj):
        addr = obj.addresses.all()
        if addr:
            ls = []
            for i in addr:
                ls.append(f"{i.province}-{i.city}")
            return ls
            # return f"{obj.real_name} {addr[0].province}"
        else:
            return "test_user"
        return f"{obj.addresses.province} {obj.user.addresses.city}"
    # 新增一个字段
    # def get_full_address(self, obj):
    #     print(obj)
    #     city = obj.addresses.city
    #     provinces = obj.addresses.province
    #     address = obj.addresses.address
    #     return f"{provinces}：{city}：{address}"
    # def to_representation(self, instance):
    #     raw_data = instance
    #     representation = super().to_representation(instance)
    #     # 自定义格式化
    #     representation['address'] = f"{instance.addresses.province}：{instance.addresses.address}"
    #     return representation
